import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:get/get.dart' as GetX;
import 'package:logger/logger.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:sports_new/server/http/request_header.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/user.dart';
import '../../controller/navigation_logic.dart';
import '../../utils/log.dart';
import '../../utils/sp_utils.dart';

class EventDio{
  static const int _timeoutDuration = 15;
  static const String _eventUrl = Constant.eventUrl;
  static final _options = BaseOptions(
      followRedirects: false,
      connectTimeout: Duration(seconds: _timeoutDuration),
      receiveTimeout: Duration(seconds: _timeoutDuration),
      sendTimeout: Duration(seconds: _timeoutDuration),
      responseType: ResponseType.json,
      baseUrl: _eventUrl
  );
  static Dio _dio = () {
    final dio = Dio(_options);
    return dio;
  }.call();

  static void init() {
    _dio = Dio(_options);
    // 代理
    (_dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () => HttpClient()
      ..badCertificateCallback = (cert, host, port) => true;
  }

  static Future<Response?> postEvent(String event, {List<dynamic>? params}) async{
    String route = GetX.Get.currentRoute;
    if(GetX.Get.currentRoute == Routes.navigation && GetX.Get.previousRoute != "/"){
      try{
        route = GetX.Get.find<NavigationLogic>().currentRoute;
      }catch(e){}
    }
    Map<String,String> json = {
      "event": event,
      "path": route,
      if(params != null)
        for(var i=0;i<params.length;i++) "param${i + 1}": params[i].toString(),
      "user_id": User.info?.id??"",
      "create_time": DateTime.now().toIso8601String(),
      "device": RequestHeader.os,
      "channel": RequestHeader.channel,
      "brand": RequestHeader.brand,
      "model": RequestHeader.model,
      "system": RequestHeader.osVersion,
      "version": RequestHeader.version,
    };
    String data = wrapEvent(json);
    try {
      // dioLog.d('dio post event: $event, encrypted:$data');
      Response response = await _dio.post("/event_log", data: {"data": data});
      // dioLog.d('Dio response event\n data: ${response.data.toString()}');
      return response;
    }catch(e){
      dioLog.d('Dio response event error\n $e');
      return null;
    }
  }

  static String wrapEvent(Json json){
    final key = encrypt.Key.fromUtf8(Constant.eventKey);
    final encrypted = encrypt.Encrypter(encrypt.AES(
      key, mode: encrypt.AESMode.ecb,
    ));
    var t = encrypted.encrypt(jsonEncode(json));
    return t.base64;
  }
}